import React from 'react';
import { Button, Toast, List, InputItem, ImagePicker, DatePicker, Radio } from 'antd-mobile';
import { createForm } from 'rc-form';
import * as request from '../request';
import ico_avatar from '../static/ico_avatar.svg';
import moment from 'moment';

const Item = List.Item;
const apiURL = "/api/services/app/Edu_Children/";
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {},
            files: [],
            loading: false,
            sex: '男',
            isUpload: false,
        }
    }
    componentDidMount() {
        var cid = parseInt(this.props.state.match.params.childid);
        const { currentChild } = this.props.state;
        if (currentChild && cid === 1) {
            this.setState({ data: currentChild, sex: currentChild.sex });
            var img = {
                url: currentChild.avatar ? request.imgServer + currentChild.avatar : ico_avatar,
                id: currentChild.avatar
            }
            this.setState({
                files: [img],
            });
            this.props.form.setFieldsValue({
                nickname: currentChild.nickname,
                name: currentChild.name,
                birthday: new Date(moment(currentChild.birthday).format('YYYY-MM-DD')),
                gweek: currentChild.gweek,
                headCirc: currentChild.headCirc,
                height: currentChild.height,
                weight: currentChild.weight,
            });
        }
    }
    onSubmit = () => {
        const { currentUser, currentChild } = this.props.state;
        const { files,isUpload } = this.state;
        var cid = parseInt(this.props.state.match.params.childid);
        this.props.form.validateFields((error, value) => {
            this.setState({ loading: true });
            if (currentUser.role === '爸爸' || currentUser.role === '父亲') {
                value.fatherId = currentUser.id;
            }
            else {
                value.motherId = currentUser.id;
            }
            if (cid === 1 && currentChild) {
                value.id = currentChild.id;
                value.avatar = currentChild.avatar;
            }
            value.birthday = moment(value.birthday).format('YYYY-MM-DD');
            value.preBirthday = moment(value.preBirthday).format('YYYY-MM-DD');
            if(!value.preBirthday || !value.gweek)
            {
                Toast.info('胎龄和预产期至少填写一项！')
                this.setState({ loading: false });
                return false;
            }
            if(value.preBirthday && !value.gweek)
            {
                value.gweek = request.getGweek(value.birthday,value.preBirthday);
            }
            value.sex = this.state.sex;
            if (!error) {
                if (files.length > 0 && isUpload) {
                    request.uploadPic(files, value.id, "Edu_children", "avatar").then((resp) => {
                        value.avatar = resp;
                        this.doAct(cid, value);
                    });
                }
                else {
                    this.doAct(cid, value);
                }

            }
            else
                this.setState({ loading: false });
        });
    }
    doAct = (cid, value) => {
        if (cid === 1) {
            this.childUpdate(value);
        }
        else {
            this.childCreate(value)
        }
    }
    childUpdate = (value) => {
        request.put(apiURL + 'Update', value).then((response) => {
            if (response) {
                if (response.success) {
                    this.props.state.dispatch({
                        type: "setCurrChild",
                        data: response.result,
                    })
                    Toast.info('更新成功！');
                }
                else {
                    Toast.fail(response.error.message);
                }
                this.setState({ loading: false });
            }
        });
    }
    childCreate = (value) => {
        request.post(apiURL + 'Create', value).then((response) => {
            if (response) {
                if (response.success) {
                    this.props.state.dispatch({
                        type: "setCurrChild",
                        data: response.result,
                    })
                    Toast.info('宝宝添加成功！');
                }
                else {
                    Toast.fail(response.error.message);
                }
                this.setState({ loading: false });
            }
        });
    }
    onChange = (files, type, index) => {
        console.log(files, type, index);
        this.setState({
            files,
            isUpload: true
        });
    }
    onChangeSex = (value) => {
        console.log('checkbox');
        this.setState({
            sex: value,
        });
    };
    render() {
        const { loading, sex, files } = this.state;
        const { getFieldProps, getFieldError } = this.props.form;
        const dataSex = [
            { value: '男', label: '男宝宝' },
            { value: '女', label: '女宝宝' },
        ];
        return (
            <form style={{ marginBottom: 60 }}>
                <List>
                    <div style={{ padding: '20px 0px 20px 40%' }}>
                        <ImagePicker
                            files={files}
                            onChange={this.onChange}
                            onImageClick={(index, fs) => console.log(index, fs)}
                            selectable={files.length < 1}
                            multiple={false}
                            accept="image/gif,image/jpeg,image/jpg,image/png"
                        /></div>
                    <InputItem
                        {...getFieldProps('nickname', {
                            rules: [
                                { required: true, message: '请输入昵称' }
                            ],
                        })}
                        placeholder="请输入昵称"
                        clear
                        error={!!getFieldError('nickname')}
                        onErrorClick={() => {
                            Toast.info(getFieldError('nickname').join('、'));
                        }}
                    >昵称</InputItem>
                    <InputItem
                        {...getFieldProps('name', {
                            rules: [
                                { required: true, message: '请输入宝宝姓名' }
                            ],
                        })}
                        placeholder="请输入宝宝姓名"
                        clear
                        error={!!getFieldError('name')}
                        onErrorClick={() => {
                            Toast.info(getFieldError('name').join('、'));
                        }}
                    >姓名</InputItem>
                    <DatePicker
                        mode="date"
                        {...getFieldProps('birthday', {
                            rules: [
                                { required: true, message: '请选择出生日期' }
                            ],
                        })}
                    >
                        <List.Item arrow="horizontal">出生日期</List.Item>
                    </DatePicker>
                    <DatePicker
                        mode="date"
                        {...getFieldProps('preBirthday')}
                    >
                        <List.Item arrow="horizontal">预产期</List.Item>
                    </DatePicker>
                    <InputItem {...getFieldProps('gweek')}  extra="周"> 胎龄 </InputItem>
                    <InputItem {...getFieldProps('headCirc')} type='money' moneyKeyboardAlign="left" extra="CM"> 头围 </InputItem>
                    <InputItem {...getFieldProps('weight')} type='money' moneyKeyboardAlign="left" extra="KG"> 体重 </InputItem>
                    <InputItem {...getFieldProps('height')} type='money' moneyKeyboardAlign="left" extra="CM"> 身高 </InputItem>
                    {dataSex.map(i => (
                        <Radio.RadioItem key={i.value} checked={sex === i.value} onChange={() => this.onChangeSex(i.value)}>
                            {i.label}
                        </Radio.RadioItem>
                    ))}
                    <Item>
                        <Button type="primary" onClick={this.onSubmit} loading={loading} disabled={!this.state.data}>提交</Button>
                    </Item>
                </List>
            </form>
        )
    };
}

export default createForm()(App);
